<template>
  <div>
    <el-radio-group v-model="pageScope" @change="handleRadioChange">
      <el-radio value="currentPage" size="large">当前页面</el-radio>
      <el-radio value="allPage" size="large">所有页面</el-radio>
    </el-radio-group>

    <!-- 当前页面使用同步模式 -->
    <el-tree
        v-if="!props.multiple && pageScope === 'currentPage'"
        :data="componentTreeData"
        node-key="id"
        highlight-current
        :props="{ children: 'children', label: 'label' }"
        @node-click="handleNodeClick"
        default-expand-all
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>{{ formatComponentType(data, null) }}</span>
        </span>
      </template>
    </el-tree>

    <!-- 所有页面使用异步模式 -->
    <el-tree
        v-if="!props.multiple && pageScope === 'allPage'"
        :data="componentTreeData"
        node-key="id"
        highlight-current
        :props="{ children: 'children', label: 'label' }"
        @node-click="handleNodeClick"
        lazy
        :load="load"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>{{ formatComponentType(data, null) }}</span>
        </span>
      </template>
    </el-tree>

    <el-tree
        v-if="props.multiple"
        :data="componentTreeData"
        node-key="id"
        show-checkbox
        :props="{ children: 'children', label: 'label' }"
        @check="handleCheckChange"
        default-expand-all
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>{{ formatComponentType(data, null) }}</span>
        </span>
      </template>
    </el-tree>

    <el-button type="primary" @click="handleConfirm">确定</el-button>
    <el-button type="success" @click="handleCancel">取消</el-button>
  </div>
</template>

<script lang="ts" setup>
import { watch, ref, inject,onMounted } from "vue";
import { vFormSchemeKey } from '@/components/form/state.key';
import { InputComponents, ButtonComponents, ContainerComponents, TableComponents, LayoutComponents } from "../../../form/designer/data";
import { listAllPage } from '@/api/business/page.js'
import { listAllFunction, isLastLevel } from '@/api/business/function.js'
import { genId } from "@/components/form/designer/util/common";

const formScheme = inject(vFormSchemeKey)!
const pageScope = ref("currentPage")

interface Node {
  id: string
  value: string
  label: string
  nodeType: string
  nodeData: string
  children?: Node[]
}

interface Emits {
  (e: 'change', selectVariable: string): void
  (e: 'cancel'): void
}

interface Props {
  multiple?: boolean
}

const props = defineProps<Props>()
const emits = defineEmits<Emits>()
const ids = ref([])
const componentTreeData = ref([]);
const selectedId = ref('');
const selectedNode = ref<Node | null>(null);
// 添加点击定时器
let clickTimer: NodeJS.Timeout | null = null;
const clickDelay = 300; // 300ms内认为是双击

watch(() => formScheme, (val) => {
  console.log('bindcomponetnselect formScheme change');
  componentTreeData.value = buildTree(formScheme.value, '');
  console.log("componentTreeData.value："+JSON.stringify(componentTreeData.value));
}, { immediate: true, deep: true })

/**
 * 构造表格树结构,暂时只实现一层下级
 * @param schema
 * @param parentName
 */
function buildTree(schema: Object, parentName: string): any[] {
  //搜索所有下级：非布局，展示，按钮组件
  let i = 0;
  let returnData = [];
  // //debugger;
  let childrens = [];
  if (schema.children) {
    childrens = schema.children;
  }
  //遍历所有子节点
  for (i = 0; i < childrens.length; i++) {
    if (childrens[i].category !== 'layout' && childrens[i].category !== 'display'
        && childrens[i].category !== 'button') {
      let tempNode = {};
      if (childrens[i].category == 'container' || childrens[i].component == 'ruoyi-ag-grid') {
        tempNode = {
          id: genId(),
          value: childrens[i].id,
          label: childrens[i].attrs.title,
          nodeType: childrens[i].component,
        }
        returnData.push(tempNode)
        let childReturnData = [];
        if (childrens[i].component == 'ruoyi-ag-grid') {
          childReturnData = buildColumnDef(childrens[i]);
        } else {
          childReturnData = buildTree(childrens[i], childrens[i].name);
        }
        if (childReturnData.length > 0) {
          tempNode.children = childReturnData;
          tempNode.hasChildren = true;
        } else {
          tempNode.hasChildren = false;
        }
      } else {
        returnData.push({
          id: genId(),
          value: childrens[i].id,
          label: childrens[i].formItemAttrs.label,
          nodeType: childrens[i].component,
          hasChildren: false
        })
      }
    } else {
      let childReturnData = buildTree(childrens[i], childrens[i].name);

      let tempNode = {
        id: genId(),
        value: childrens[i].id,
        label: childrens[i].formItemAttrs ? childrens[i].formItemAttrs.label : childrens[i].category,
        nodeType: childrens[i].component,
        children: []
      };
      if (childReturnData.length > 0) {
        tempNode.children = childReturnData;
        tempNode.hasChildren = true;
      } else {
        tempNode.hasChildren = false;
      }
      returnData.push(tempNode)
    }
  }
  return returnData;
}

/**
 * 填充id属性
 * @param data
 */
function fillIdProps(data) {
  for (let i = 0; i < data.length; i++) {
    data[i].id = genId();
  }
  return data;
}

const load = async (
    node: Node,
    resolve: (data: Node[]) => void
) => {
  // 如果是页面节点
  if (node.nodeType == 'page') {
    let formScheme1 = JSON.parse(node.nodeData);
    let children = buildTree(formScheme1, '');
    resolve(children)
    // 如果是业务节点
  } else if (node.nodeType == 'bs') {
    // 判断是否为末级节点
    let query = { businessCode: node.value }
    let res = await isLastLevel(query);
    if (res.code == 200) {
      // 如果是末级，则查询业务功能下的页面列表
      if (res.data == true) {
        let query = { businessCode: node.value }
        let res1 = await listAllPage(query);
        if (res1.code == 200) {
          let children = fillIdProps(res1.data)
          resolve(children)
        }
      } else {
        // 查询下级业务功能节点
        let query = { parentCode: node.value }
        let res1 = await listAllFunction(query);
        if (res1.code == 200) {
          let children = fillIdProps(res1.data)
          resolve(children)
        }
      }
    }
  } else {
    resolve(node.children || [])
  }
}

/**
 * 构造指定表的列列表
 * @param agGrid
 */
function buildColumnDef(agGrid) {
  // 循环表格字段列表
  let columnDef = [];

  for (let i = 0; i < agGrid.attrs.columnDefs.length; i++) {
    let tempNode = {
      id: genId(),
      value: agGrid.attrs.columnDefs[i].field,
      label: agGrid.attrs.columnDefs[i].headerName,
      nodeType: 'ruoyi-ag-grid-field',
    }
    columnDef.push(tempNode)
  }
  return columnDef;
}

/**
 * 单击节点
 * @param data
 */
function handleNodeClick(data: Node) {
  // 清除之前的定时器
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;

    // 双击事件处理
    handleNodeDblclick(data);
  } else {
    // 设置定时器，延迟执行单击事件
    clickTimer = setTimeout(() => {
      // 单击事件处理
      selectedNode.value = data;
      selectedId.value = data.value;
      console.log('handleNodeClick:' + selectedId.value);
      clickTimer = null;
    }, clickDelay);
  }
}

/**
 * 节点选中状态改变
 * @param data
 * @param checkedInfo
 */
function handleCheckChange(data: Node, checkedInfo: { checkedNodes: Node[] }) {
  ids.value = checkedInfo.checkedNodes.map(item => item.value);
}

/**
 *  单击确认按钮
 */
function handleConfirm() {
  console.log('handleConfirm:' + selectedId.value)
  if (!props.multiple) {
    emits('change', selectedId.value)
  } else {
    emits('change', ids.value.toString())
  }
}

/**
 *  单击取消按钮
 */
function handleCancel() {
  emits('cancel')
}

function handleNodeDblclick(data: Node) {
  selectedNode.value = data;
  selectedId.value = data.value;
  handleConfirm();
}

/**
 * 翻译组件类型
 * @param row
 * @param column
 * @returns {*|string}
 */
function formatComponentType(row: any, column: any) {
  let i = 0;
  // console.log('row.nodeType:'+row.nodeType)
  // console.log('InputComponents:'+JSON.stringify(InputComponents))
  for (i = 0; i < InputComponents.length; i++) {
    if (row.nodeType === InputComponents[i].component) {
      return InputComponents[i].title;
    }
  }
  for (i = 0; i < ButtonComponents.length; i++) {
    if (row.nodeType === ButtonComponents[i].component) {
      return ButtonComponents[i].title;
    }
  }
  for (i = 0; i < ContainerComponents.length; i++) {
    if (row.nodeType === ContainerComponents[i].component) {
      return ContainerComponents[i].title;
    }
  }
  for (i = 0; i < TableComponents.length; i++) {
    if (row.nodeType === TableComponents[i].component) {
      return TableComponents[i].title;
    }
  }
  for (i = 0; i < LayoutComponents.length; i++) {
    if (row.nodeType === LayoutComponents[i].component) {
      return LayoutComponents[i].title;
    }
  }
  if (row.nodeType == 'bs') {
    return '业务'
  } else if (row.nodeType == 'page') {
    return '页面'
  } else if (row.nodeType == 'el-col') {
    return '格子'
  } else if (row.nodeType == 'ruoyi-ag-grid-field') {
    return '表格列'
  }
  return '';
}

const handleRadioChange = async (value) => {
  if (value == 'currentPage') {
    componentTreeData.value = buildTree(formScheme.value, '');
  } else {
    // 调用接口查询数据
    let queryJson = { firstTop: '1' }
    let res = await listAllFunction(queryJson);
    if (res.code == 200) {
      componentTreeData.value = fillIdProps(res.data);
    } else {
      componentTreeData.value = [];
    }
  }
}
onMounted(() => {
  handleRadioChange("currentPage")
})
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node span:last-child {
  margin-left: 20px;
  color: #999;
}
</style>
